package com.huike.clues.MpService.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.huike.clues.MpMapper.*;
import com.huike.clues.MpService.MpSysRoleService;
import com.huike.clues.domain.dto.MPSysRoleDto;
import com.huike.clues.domain.result.PageResult;
import com.huike.clues.mapper.SysRoleMapper;
import com.huike.common.core.page.PageDomain;
import com.huike.common.core.page.TableSupport;
import com.huike.common.entity.*;
import com.huike.common.utils.SecurityUtils;
import com.huike.common.utils.StringUtils;
import com.huike.common.utils.bean.BeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class MpSysRoleServiceImpl extends ServiceImpl<SysRoleMapper, MPSysRole> implements MpSysRoleService {

    @Resource
    private MpSysRoleMapper mpSysRoleMapper;

    @Resource
    private MpSysMenuMapper mpSysMenuMapper;

    @Resource
    private MpSysDeptMapper mpSysDeptMapper;

    @Resource
    private MPSysRoleDeptMapper mpSysRoleDeptMapper;

    @Resource
    private MpSysRoleMenuMapper mpSysRoleMenuMapper;

    /**
     * 分页查询角色列表
     *
     * @param
     * @return
     */
    @Override
    public PageResult roleList(MPSysRole mpSysRole) {
        //接收前端page信息
        PageDomain pageDomain = TableSupport.buildPageRequest();
//        //使用pagehelper插件分页
        PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize());
//        Page<MPSysRole> page = new Page<>(pageDomain.getPageNum(), pageDomain.getPageSize());

        //创建一个wrapper
        QueryWrapper<MPSysRole> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.isNotEmpty(mpSysRole.getRoleName()),
                "role_name", mpSysRole.getRoleName());
        wrapper.like(StringUtils.isNotEmpty(mpSysRole.getRoleKey()),
                "role_key", mpSysRole.getRoleKey());
//        wrapper.eq(StringUtils.isNotEmpty(mpSysRole.getStatus()),
//                "status", mpSysRole.getStatus());
        if (mpSysRole.getParams() != null) {
            wrapper.ge(ObjectUtils.isNotEmpty(mpSysRole.getParams().get("beginTime")),
                    "create_time", mpSysRole.getParams().get("beginTime"));
            wrapper.le(ObjectUtils.isNotEmpty(mpSysRole.getParams().get("endTime")),
                    "create_time", mpSysRole.getParams().get("endTime"));
        }
        List<MPSysRole> sysRoles = mpSysRoleMapper.selectList(wrapper);
        Page<MPSysRole>page=(Page<MPSysRole>)sysRoles;

        //返回List
        return new PageResult(page.getTotal(),page.getResult());
    }

    /**
     * 新增角色
     *
     * @param
     */
    @Override
    public void addRole(MPSysRoleDto mpSysRoleDto) {
        //把sysRole的数据新增进数据库中
        MPSysRole mpSysRole = new MPSysRole();
        BeanUtils.copyProperties(mpSysRoleDto, mpSysRole);
        mpSysRole.setCreateTime(LocalDateTime.now());
        mpSysRole.setUpdateTime(LocalDateTime.now());
        mpSysRole.setCreateBy(SecurityUtils.getUsername());
        mpSysRole.setUpdateBy(SecurityUtils.getUsername());
        mpSysRoleMapper.insert(mpSysRole);
        log.info("id:{}",mpSysRole.getRoleId());
        //如果新增的部门iD不为空
        if (mpSysRoleDto.getDeptIds() != null || mpSysRoleDto.getDeptIds().length > 0) {
            //直接把部门id放入sys_role_mune中
            Long[] deptIds = mpSysRoleDto.getDeptIds();
            for (int i = 0; i < deptIds.length; i++) {
                MPSysRoleDept mpSysRoleDept = new MPSysRoleDept();
                mpSysRoleDept.setRoleId(mpSysRole.getRoleId());
                mpSysRoleDept.setDeptId(deptIds[i]);
                mpSysRoleDeptMapper.insert(mpSysRoleDept);
            }
        }

        //如果新增的菜单ID不为NULL
        if (mpSysRoleDto.getMenuIds() != null || mpSysRoleDto.getMenuIds().length > 0) {
            //直接把部门id放入sys_role_mune中
            Long[] menuIds = mpSysRoleDto.getMenuIds();
            for (int i = 0; i < menuIds.length; i++) {
                MPSysRoleMenu mpSysRoleMenu = new MPSysRoleMenu();
                mpSysRoleMenu.setRoleId(mpSysRole.getRoleId());
                mpSysRoleMenu.setMenuId(menuIds[i]);
                log.info("菜单id：{}",menuIds[i]);
                mpSysRoleMenuMapper.insert(mpSysRoleMenu);
            }
        }
    }

    /**
     * 根据角色编号获取详细信息
     * @param roleId
     * @return
     */
    @Override
    public MPSysRoleDto selectById(Integer roleId) {
        //根据roldId查询role对象
        MPSysRole mpSysRole = mpSysRoleMapper.selectById(roleId);
        MPSysRoleDto mpSysRoleDto = new MPSysRoleDto();
        BeanUtils.copyProperties(mpSysRole,mpSysRoleDto);
        //根据roldID查询与menu的关系表
        QueryWrapper<MPSysRoleMenu> wrapper = new QueryWrapper<>();
        wrapper.eq("role_id",roleId);
        List<MPSysRoleMenu> menuList = mpSysRoleMenuMapper.selectList(wrapper);
        Long[] menuIds = mpSysRoleDto.getMenuIds();
        menuList.forEach(mpSysRoleMenu -> {
            for (int i = 0; i < menuIds.length; i++) {
            Long menuId = mpSysRoleMenu.getMenuId();
                menuIds[i]=menuId;
            }
        });
        mpSysRoleDto.setMenuIds(menuIds);

        //根据roldId查询与dept的关系表
        QueryWrapper<MPSysRoleDept> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("role_id",roleId);
        List<MPSysRoleDept> deptList = mpSysRoleDeptMapper.selectList(wrapper1);
        Long[] deptIds = mpSysRoleDto.getDeptIds();
        deptList.forEach(mpSysRoleDept -> {
            for (int i = 0; i < deptIds.length; i++) {
                Long deptId = mpSysRoleDept.getDeptId();
                deptIds[i]=deptId;
            }
        });
        mpSysRoleDto.setDeptIds(deptIds);
        return mpSysRoleDto;
    }

    /**
     * 修改保存角色
     * @param mpSysRoleDto
     */
    @Override
    public void updateRole(MPSysRoleDto mpSysRoleDto) {
        //根据传进来的数据修改保存角色
        //创建一个MPSysRole对象
        MPSysRole mpSysRole = new MPSysRole();
        //把传入的数据赋值给MPSysRole对象
        BeanUtils.copyProperties(mpSysRoleDto,mpSysRole);
        mpSysRole.setUpdateTime(LocalDateTime.now());
        mpSysRole.setUpdateBy(SecurityUtils.getUsername());
        //修改数据
        mpSysRoleMapper.updateById(mpSysRole);
        //重新插入传进来的关系表数据
        //直接把部门id放入sys_role_dept中
        Long[] deptIds = mpSysRoleDto.getDeptIds();
        if (deptIds!=null&&deptIds.length>0) {
        //删除所有关系表数据
        mpSysRoleDeptMapper.deleteById(mpSysRole.getRoleId());
            for (int i = 0; i < deptIds.length; i++) {
                MPSysRoleDept mpSysRoleDept = new MPSysRoleDept();
                mpSysRoleDept.setRoleId(mpSysRole.getRoleId());
                mpSysRoleDept.setDeptId(deptIds[i]);
                mpSysRoleDeptMapper.insert(mpSysRoleDept);
            }
        }
        //直接把部门id放入sys_role_menu中
        Long[] menuIds = mpSysRoleDto.getMenuIds();
        if (menuIds!=null&&menuIds.length>0) {
        mpSysRoleMenuMapper.deleteById(mpSysRole.getRoleId());
            for (int i = 0; i < menuIds.length; i++) {
                MPSysRoleMenu mpSysRoleMenu = new MPSysRoleMenu();
                mpSysRoleMenu.setRoleId(mpSysRole.getRoleId());
                mpSysRoleMenu.setMenuId(menuIds[i]);
                log.info("菜单id：{}", menuIds[i]);
                mpSysRoleMenuMapper.insert(mpSysRoleMenu);
            }
        }
    }

    /**
     * 状态修改
     * @param mpSysRoleDto
     */
    @Override
    public void updateByStatus(MPSysRoleDto mpSysRoleDto) {
        MPSysRole mpSysRole = new MPSysRole();
        BeanUtils.copyProperties(mpSysRoleDto,mpSysRole);
        mpSysRole.setUpdateTime(LocalDateTime.now());
        mpSysRole.setUpdateBy(SecurityUtils.getUsername());
        MPSysRole mpSysRole1 = mpSysRoleMapper.selectById(mpSysRole);
        if (mpSysRole1.getStatus().equals("0")){
            mpSysRole.setStatus("1");
        }else {
            mpSysRole.setStatus("0");
        }

        mpSysRoleMapper.updateById(mpSysRole);
    }

    /**
     * export
     * @param mpSysRoleDto
     */
    @Override
    public void export(MPSysRoleDto mpSysRoleDto) {

    }

    /**
     * 获取角色选择框列表
     * @return
     */
    @Override
    public List<MPSysRoleDto> optionselect() {
        //通过selectlist获得所有role的值
        List<MPSysRole> sysRoles = mpSysRoleMapper.selectList(null);
        //创建dto集合用于接受遍历集合中的值
        List<MPSysRoleDto>sysRoleDtoList=new ArrayList<>();
        //遍历集合，在集合中获得对应的关联表的值
        sysRoles.forEach(mpSysRole -> {
            MPSysRoleDto mpSysRoleDto = new MPSysRoleDto();
            //根据roleid获得对应关联表的集合
            QueryWrapper<MPSysRoleDept> wrapper = new QueryWrapper<>();
            wrapper.eq("role_id",mpSysRole.getRoleId());
            List<MPSysRoleDept> mpSysRoleDepts = mpSysRoleDeptMapper.selectList(wrapper);
            //遍历集合通过遍历对deptIdS进行赋值，再赋值给dto
            mpSysRoleDepts.forEach(mpSysRoleDept -> {
            Long[] deptIds=mpSysRoleDto.getDeptIds();
                for (int i = 0; i <deptIds.length; i++) {
                    deptIds[i]=mpSysRoleDept.getDeptId();
                }
                mpSysRoleDto.setDeptIds(deptIds);
            });
            //和上面一样的过程
            QueryWrapper<MPSysRoleMenu> wrapper1 = new QueryWrapper<>();
            List<MPSysRoleMenu> mpSysRoleMenus = mpSysRoleMenuMapper.selectList(wrapper1);
            mpSysRoleMenus.forEach(mpSysRoleMenu -> {
                Long[] menuIds = mpSysRoleDto.getMenuIds();
                for (int i = 0; i < menuIds.length; i++) {
                    menuIds[i]=mpSysRoleMenu.getMenuId();
                }
                mpSysRoleDto.setMenuIds(menuIds);
            });
        });
        //把MPSysRole集合中的原始赋值给mpSysRoleDto集合
        BeanUtils.copyProperties(sysRoles,sysRoleDtoList);
        return sysRoleDtoList;
    }

    /**
     * 修改保存数据权限
     * @param mpSysRoleDto
     */
    @Override
    public void dataScope(MPSysRoleDto mpSysRoleDto) {
        MPSysRole mpSysRole = new MPSysRole();
        BeanUtils.copyProperties(mpSysRoleDto,mpSysRole);
        mpSysRole.setUpdateTime(LocalDateTime.now());
        mpSysRole.setUpdateBy(SecurityUtils.getUsername());
        mpSysRoleMapper.updateById(mpSysRole);
    }


    /**
     * 删除角色
     * @param roldIds
     */
    @Override
    public void deleteById(List<Long> roldIds) {
        //根据id获得对应的对象
        List<MPSysRole> sysRoles = mpSysRoleMapper.selectBatchIds(roldIds);
        //遍历集合
        sysRoles.forEach(mpSysRole -> {
            //判断集合中是否存在启用状态的对象，如果有，提醒客户，如果没有，就直接删除
            if (mpSysRole.getStatus().equals("1")){
                throw new RuntimeException("有启用状态的对象，不能删除");
            }
        });
        //根据ID批量删除数据
        mpSysRoleMapper.deleteBatchIds(roldIds);
        //根据ID批量删除部门关系表数据
        mpSysRoleDeptMapper.deleteBatchIds(roldIds);
        //根据ID批量删除权限关系表
        mpSysRoleMenuMapper.deleteBatchIds(roldIds);
    }


}






